#!/bin/bash
#
# Author:   Dr. Mike Murphy (mmurphy2@coastal.edu)
# Revision: 11 November 2013
#
#   Copyright 2012-2013 Coastal Carolina University
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#


declare -a -g P_AGENT_SCRIPT_SCRIPTS


## p_agent_script_help
##
## Echoes help information for the script agent. Returns 0.
##
function p_agent_script_help() {
	cat << EOF
Runs arbitrary scripts, functions, or commands, as specified in the
subscription. Commands and scripts that are not embedded as functions in
the subscription file itself must already be present on the system prior
to agent execution.
EOF
	return 0
}


## p_agent_script_summary
##
## Echoes summary information for the script agent. Returns 0.
##
function p_agent_script_summary() {
	echo "Runs scripts, functions, or commands supplied by the subscription"
	return 0
}


## p_agent_script_check
##
## Update checking is unsupported for scripts. Returns 0.
##
function p_agent_script_check() {
	return 0
}


## p_agent_script_run
##
## Runs scripts that have been previously enabled. Returns 0 on success,
## non-zero if an error occurs.
##
function p_agent_script_run() {
	echo "Executing scripts..."
	local status=0
	local final_status=0
	for script in "${P_AGENT_SCRIPT_SCRIPTS[@]}"; do
		echo "Executing script: ${script}"
		${script}
		status=$?
		echo "Script exited with status: ${status}"
		[ ${final_status} -eq 0 ] && [ ${status} -ne 0 ] && final_status=${status}
	done
	return ${final_status}
}


## enable_script <name>
##
##
function enable_script() {
	P_AGENT_SCRIPT_SCRIPTS+=("$1")
}
